﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using BoolanElement.Storage;
using BoolanSlide.BooCommon;
using BoolanSlide.FileManager;
using BoolanSlide.FileManager.ThumbNails;
using BoolanSlide.FileStruct;
using BoolanSlide.Language;
using Configuration;
using Windows.Storage;

namespace BoolanElement
{
    public class DocumentStorage
    {
        private ThumbNailsHelper thumbNailsHelper;

        private SelectBPTTemplate SelectBptTemplate;

        public DocumentStorage(SlideIndexChangedHandler slideIndexChangedHandler)
        {
            thumbNailsHelper = new ThumbNailsHelper(GlobalVariable.ThumbNails);
            thumbNailsHelper.SlideIndexChanged += slideIndexChangedHandler;
        }

        public async Task<bool> CreateFile(BPTFileInformation fileInfomation)
        {
            WaitingForLoad.IsWaitingForLoad = true;



            Configuration.GlobalVariable.OpenedDocument = await BooDocumentHelper.NewFile(fileInfomation);
            thumbNailsHelper.LoadThumbNailsFormDocument(Configuration.GlobalVariable.OpenedDocument);


            SelectBptTemplate = new SelectBPTTemplate();
            await SelectBptTemplate.LoadTemplate(fileInfomation.FileName);

            SelectBptTemplate.addSlide = AddSlide;



            ShowFileName(LanguageManager.NewDocument + Configuration.GlobalVariable.FileExtension);


            await SelectBptTemplate.AddFirstSlide();

            ThumbNailsItem thumbNailsItem = new ThumbNailsItem(null, null);
            GlobalVariable.ThumbNails.Children.Add(thumbNailsItem);


            WaitingForLoad.IsWaitingForLoad = false;
            AutoSaveHelper.StartupAutoSave();
            BooLog.Log("Startup AutoSave");

            return true;
        }

        public void AddSlide()
        {
            bool isShow = SelectBptTemplate.IsShow;

            LostFocusObserver.Invoke();

            SelectBptTemplate.IsShow = !isShow;
        }

        public async Task<bool> OpenFileFromLibrary(BPTFileInformation fileInfomation)
        {
            WaitingForLoad.IsWaitingForLoad = true;

            //thumbNailsHelper.Reset();
            GlobalVariable.MainCanvas.Children.Clear();


            if (fileInfomation.FileSavedPosition == BPTFileInformation.FilePosition.FromLibrary)
            {
                Configuration.GlobalVariable.OpenedDocument = await BooDocumentHelper.FromLibrary(fileInfomation.FileName);
            }
            else if (fileInfomation.FileSavedPosition == BPTFileInformation.FilePosition.Pick)
            {
                Configuration.GlobalVariable.OpenedDocument = await BooDocumentHelper.FromFileSystem(fileInfomation.File);
                Configuration.GlobalVariable.OpenedDocument.FileInformation.FileSavedPosition = BPTFileInformation.FilePosition.Pick;
            }


            Configuration.FileAttributes.Ratio = Configuration.GlobalVariable.OpenedDocument.FileInformation.Resolution;

            BPTFileInformation fileinfo = null;

            fileinfo = await BooLibrary.GetThemeInformationByGUID(Configuration.GlobalVariable.OpenedDocument.FileInformation.ThemeGuid);


            SelectBptTemplate = new SelectBPTTemplate();
            await SelectBptTemplate.LoadTemplate(fileinfo.FileName);
            SelectBptTemplate.addSlide = AddSlide;

            ThumbNailsItem thumbNailsItem = new ThumbNailsItem(null, null);
            GlobalVariable.ThumbNails.Children.Add(thumbNailsItem);
           
            thumbNailsHelper.LoadThumbNailsFormDocument(Configuration.GlobalVariable.OpenedDocument);

            ShowFileName(fileInfomation.FileName);

            WaitingForLoad.IsWaitingForLoad = false;
            AutoSaveHelper.StartupAutoSave();
            

            return true;
        }

        public async Task<bool> SaveFile()
        {
            if (Configuration.GlobalVariable.OpenedDocument == null)
                return false;

            await Save(Configuration.GlobalVariable.OpenedDocument);
            return true;
        }

        public static async Task<bool> Save(BooDocument doc,StorageFolder folder = null, string SaveName = null)
        {
            List<String> ImageFiles = new List<string>();
            await StorageLock.WaitSignal.WaitAsync();
            BooDocumentInMemory InMemoryDocument = new BooDocumentInMemory();
            InMemoryDocument.summaryBlock.Load(doc.Summary());
            InMemoryDocument.summaryBlock.FileName = "summary.xml";
            InMemoryDocument.SlideBlocks.Clear();
            for (int i = 0; i < doc.Slides.Count; ++i)
            {
                XDocument slide = doc.Slides[i].Save();
                if (!ImageFiles.Contains(doc.Slides[i].BackgroundImagePath))
                    ImageFiles.Add(doc.Slides[i].BackgroundImagePath);
                foreach (BooElement ele in doc.Slides[i].Elements)
                {
                    if (ele is BooPictureElement)
                    {
                        if (!ImageFiles.Contains((ele as BooPictureElement).filePath))
                            ImageFiles.Add((ele as BooPictureElement).filePath);
                    }
                }
                BPTFileBlock block = new BPTFileBlock();
                block.Load(slide.ToString());
                block.GroupName = "slides";
                block.FileName = "slide" + i + ".xml";
                InMemoryDocument.SlideBlocks.Add(block);
            }

            if (SaveName == null || SaveName == "")
            {
                SaveName = doc.FileInformation.FileName;
            }

            if (folder == null)
                folder = await BooUtility.GetFolderFromDocumentFolderAsync(BooDocumentHelper.LibraryFolder);

            StorageFile desFile = null;

            if (doc.FileInformation.FileSavedPosition == BPTFileInformation.FilePosition.FromLibrary)
            {
                try
                {
                    desFile = await folder.CreateFileAsync(SaveName, CreationCollisionOption.OpenIfExists);
                }
                catch (Exception e)
                {
                }
            }
            else if (doc.FileInformation.FileSavedPosition == BPTFileInformation.FilePosition.Pick)
            {
                DateTime saveTime = System.DateTime.Now;

                string timeString = saveTime.ToString("MMddhhmm");

                string Name = SaveName.Insert(SaveName.Length - 3, timeString);

                desFile = await folder.CreateFileAsync(Name, CreationCollisionOption.GenerateUniqueName);
            }


            await BPTFile.SaveToFile(desFile, InMemoryDocument, ImageFiles);

            StorageLock.WaitSignal.Release();
            return true;
        }

        private async Task<bool> AddSlide(BooSlide booSlide)
        {
            return await thumbNailsHelper.AddSlide(booSlide);
        }

        private void ShowFileName(string fileName)
        {
            int len = fileName.Length;

            string NameWithoutExtensions = fileName.Substring(0, len - 3);

            GlobalVariable.DocumentTitle.Text = NameWithoutExtensions;
        }

        public void Reset(SlideIndexChangedHandler slideIndexChangedHandler)
        {
            thumbNailsHelper.Reset();

            SelectBptTemplate = null;
        }

        public async Task<bool> NextSlide()
        {
            if (thumbNailsHelper == null)
                return false;

            await thumbNailsHelper.NextSlide();
            return true;
        }

        public async Task<bool> PreviewSlide()
        {
            if (thumbNailsHelper == null)
                return false;
            await thumbNailsHelper.PreviewSlide();
            return true;
        }
    }
}
